/*
 * @Author: your name
 * @Date: 2021-09-17 11:20:36
 * @LastEditTime: 2021-09-17 11:29:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \media_system\utils\common.js
 */
const mimetype = require('mimetype');
const fs = require('fs');
const sharp = require('sharp');
const path = require('path');
sharp.cache(false);
function formatResponse(code, data, message) {
  return { code, data, message }
}
async function resizeImg(item) {
  const type = path.extname(item.filename)
  const filename = item.filename.replace(type, '')
  const url = path.join(item.destination, filename)
  const mimeType = mimetype.lookup(item.path)
  const data = await sharp(item.path).resize(96, 96).toBuffer()
  let base64str = 'data:' + mimeType + ';base64,' + Buffer.from(data).toString('base64');
  return base64str
}
async function resizeAvator() {
  //随机获取头像的图片名称
  let num = Math.floor(Math.random() * 6 + 1)
  const data = await sharp(path.join(__dirname,`../public/avators/h${num}.jpg`)).resize(128, 128).toBuffer()
  let base64str = 'data:jpeg;base64,' + Buffer.from(data).toString('base64');
  return base64str

}
function filterColumn(body) {
  //过滤请求字段，去除内容为空字符的字段
  let result = {}
  for (var key in body) {
    if (body[key] && body[key] != "") {
      result[key] = body[key]
    }
  }
  return result
}

// function decodeUnicode(str) {
//   return unescape(str.replace(/\\u/gi, '%u'))
// }

// function encodeUnicode(str) {
//   let res = [];
//   for (let i = 0; i < str.length; i++) {
//       res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
//   }
//   return  "\\u" + res.join("\\u");
// }
module.exports = {
  formatResponse, resizeImg,filterColumn,resizeAvator
}
